package com.launcher.wkang.receive;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.LinkProperties;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.launcher.wkang.App;
import com.launcher.wkang.util.NetUtils;
import com.launcher.wkang.util.PhoneUtil;
import com.launcher.wkang.util.Url;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static cn.jpush.android.api.JPushInterface.getRegistrationID;
//
//import io.rong.push.notification.PushMessageReceiver;
//import io.rong.push.notification.PushNotificationMessage;

public class PushReceive  extends BroadcastReceiver {
    /* 下载保存路径 */
    private String mSavePath, downloadVersion;
    private String downLoadUrl;
    /* 是否取消更新 */
    private boolean cancelUpdate = false;
    private final String MESSAGE_REGISTRATION_ID="cn.jpush.android.intent.REGISTRATION";

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
        String  getBroadcast=intent.getStringExtra("getBroadcast");
        Log.d("PushReceive","getBroadcast="+getBroadcast);
        Log.d("PushReceive","PushReceiveonReceive");
        Log.d("PushReceive","message="+message);
        Log.d("PushReceive","PushReceive Action="+intent.getAction());
        if("cn.jpush.android.intent.CONNECTION".equals(intent.getAction())){
            JPushInterface.setDebugMode(true);
            JPushInterface.init(context);
            return;
        }

        if (!TextUtils.isEmpty(message)){
            try {
                JSONObject jsonObject=new JSONObject(message);
                if (jsonObject!=null){
                    String mark=jsonObject.optString("mark");
                    String operate=jsonObject.optString("operate");
                    if ("contact".equalsIgnoreCase(mark)){
                        String contactName=jsonObject.optString("contactName");
                        String contactPhone=jsonObject.optString("contactPhone");
                        int id=jsonObject.optInt("id");
                        if ("save".equalsIgnoreCase(operate)){
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                if(context.checkSelfPermission(Manifest.permission.WRITE_CONTACTS)==PackageManager.PERMISSION_GRANTED){
                                    // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
                                    PhoneUtil.addContact(context,contactName,contactPhone,id);
                                }else {
                                    Toast.makeText(context, "请添加允许添加联系人权限", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                        if ("update".equalsIgnoreCase(operate)){
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                if(context.checkSelfPermission(Manifest.permission.WRITE_CONTACTS)==PackageManager.PERMISSION_GRANTED){
                                    // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
                                    PhoneUtil.updateContact(context,contactName,contactPhone,id);
                                }else {
                                    Toast.makeText(context, "请添加允许添加联系人权限", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                        if ("delete".equalsIgnoreCase(operate)){
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                if(context.checkSelfPermission(Manifest.permission.WRITE_CONTACTS)==PackageManager.PERMISSION_GRANTED){
                                    // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
                                    PhoneUtil.deleteContact(context,id);
                                }else {
                                    Toast.makeText(context, "请添加允许添加联系人权限", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }

                    }
                    if ("installApp".equalsIgnoreCase(mark)){
                        downLoadUrl=jsonObject.optString("downloadUrl");
                        int appId=jsonObject.optInt("userappId");
                        new DownloadApkThread(context,appId).start();
                    }
                    if ("uninstallApp".equalsIgnoreCase(mark)){
                        SharedPreferences sharedPreferences = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
                        String  packageNameList = sharedPreferences.getString("packageNameList", null);
                        String userappId=jsonObject.optString("userappId");
                        if (!TextUtils.isEmpty(packageNameList)){
                            JSONArray jsonArray=new JSONArray(packageNameList);
                            if (jsonArray!=null&&jsonArray.length()>0){
                                for(int i=0;i<jsonArray.length();i++) {
                                    JSONObject packageNameItem =jsonArray.getJSONObject(i);
                                    String packageName=packageNameItem.optString(userappId);
                                    if (!TextUtils.isEmpty(packageName)){
                                        Uri uri=Uri.parse("package:"+packageName);
                                        Intent intentdel = new Intent(Intent.ACTION_DELETE, uri);
                                        context.startActivity(intentdel);
                                        break;
                                    }
                                }
                            }
                        }

                    }
                    if ("phoneLossReporting".equalsIgnoreCase(mark)){
                        SharedPreferences sharedPreferences =context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        String lostStatus=jsonObject.optString("lostStatus");
                        editor.putString("lostStatus",lostStatus);
                        editor.commit();
                    }
                    if ("disableDevice".equalsIgnoreCase(mark)){
                        int disableClass=jsonObject.optInt("disableClass");
                        SharedPreferences sharedPreferences =context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putInt("disableClass",disableClass);
                        editor.commit();
                        if (disableClass==2){

                            String repeat=jsonObject.optString("repeat");
                            String amstarttime=jsonObject.optString("amstarttime");
                            String amendtime=jsonObject.optString("amendtime");

                            String pmstarttime=jsonObject.optString("pmstarttime");
                            String pmendtime=jsonObject.optString("pmendtime");

                            String gnstarttime=jsonObject.optString("gnstarttime");
                            String gnendtime=jsonObject.optString("gnendtime");

                            editor.putString("repeat",repeat);

                            editor.putString("amstarttime",amstarttime);
                            editor.putString("amendtime",amendtime);

                            editor.putString("pmstarttime",pmstarttime);
                            editor.putString("pmendtime",pmendtime);

                            editor.putString("gnstarttime",gnstarttime);
                            editor.putString("gnendtime",gnendtime);
                            editor.commit();

                        }
                    }
                    if ("reservePower".equalsIgnoreCase(mark)){
                        String electricityStatus=jsonObject.optString("electricityStatus");
                        SharedPreferences sharedPreferences =context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putString("electricityStatus",electricityStatus);
                        editor.commit();
                    }
                    if ("addwebsite".equalsIgnoreCase(mark)||"delwebsite".equalsIgnoreCase(mark)||"updatewebsite".equalsIgnoreCase(mark)){
//                        String name=jsonObject.optString("name");
//                        int id=jsonObject.optInt("id");
//                        String url=jsonObject.optString("url");
//                        BookMarketUtil.insertBookMark(context,id,name,url);
                        Intent browserIntent=new Intent("bookmarkreceiver");
                        browserIntent.putExtra("message",message);
                        context.sendBroadcast(browserIntent);
                    }
//                    修改或者添加
                    if ("course".equalsIgnoreCase(mark)){
                        Intent browserIntent=new Intent("CourseReceiver");
                        context.sendBroadcast(browserIntent);

                    }
                    if("stuInfo".equalsIgnoreCase(mark)){
                        String stuName=jsonObject.optString("stuName");
                        String stuIcon=jsonObject.optString("stuIcon");
                        String grade=jsonObject.optString("grade");
                        String school=jsonObject.optString("school");
                        String stuClass=jsonObject.optString("stuClass");
                        SharedPreferences sharedPreferences =context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putString("stuName",stuName);
                        editor.putString("stuIcon",stuIcon);
                        editor.putString("grade",grade);
                        editor.putString("school",school);
                        editor.putString("stuClass",stuClass);
                        editor.commit();

                    }
                    if ("timeSwitch".equalsIgnoreCase(mark)){
                        String format = "HH:mm";
                        String autoOpenDate=jsonObject.optString("autoOpenDate");
                        String autoCloseDate=jsonObject.optString("autoCloseDate");
                        int autoStasus=jsonObject.optInt("autoStasus");
                        Date autoOpenTimeDate = null;
                        Date autoCloseTimeDate=null;
                        try {

                                autoOpenTimeDate = new SimpleDateFormat(format).parse(autoOpenDate);
                                autoCloseTimeDate = new SimpleDateFormat(format).parse(autoCloseDate);
                                int openHour = autoOpenTimeDate.getHours();
                                int openMinute = autoOpenTimeDate.getMinutes();
                                int closeHour = autoCloseTimeDate.getHours();
                                int closeMinute = autoCloseTimeDate.getMinutes();
                            if (autoStasus==1) {
                                PhoneUtil.startUp(openHour, openMinute, context);
                                PhoneUtil.shutDown(closeHour, closeMinute, context);
                            }else {
                                PhoneUtil.cacellShutDown(context);
                                PhoneUtil.cacellStartUp(context);
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }


                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

    private class DownloadApkThread extends Thread {
        private Context context;
        private int appId;
        public DownloadApkThread(Context context,int appId){
            this.context=context;
            this.appId=appId;
        }
        @Override
        public void run() {
            // 判断SD卡是否存在，并且是否具有读写权限
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                // 获得存储卡的路径
                String sdpath = Environment.getExternalStorageDirectory() + "/";
                mSavePath = sdpath + "Download";
                URL url = null;
                try {
                    url = new URL(downLoadUrl);
                    HttpURLConnection conn = null;
                    conn = (HttpURLConnection) url.openConnection();
                    conn.connect();      // 获取文件大小
                    int length = conn.getContentLength();
                    InputStream is = conn.getInputStream();    // 创建输入流
                    File file = new File(mSavePath);
                    if (!file.exists()) {    // 判断文件目录是否存在
                        file.mkdir();
                    }
                    // 创建连接

                    File apkFile = new File(mSavePath, "mobilelife.apk");
//                    installApk(context);
//
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    byte buf[] = new byte[1024];   // 缓存
                    do {      // 写入到文件中
                        int numread = is.read(buf);
                        count += numread;

                        if (numread <= 0) {

                            installApk(context,appId);
//                            File file1 = new File(mSavePath, "mobilelife.apk");
//                            Operate.installSilent(file1.getPath());
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    /**
     * 安装APK文件
     */
//    private void installApk(Context context) {
//
//
//        File apkfile = new File(mSavePath, "mobilelife.apk");
//        if (!apkfile.exists()) {
//            return;
//        }
//        // 通过Intent安装APK文件
//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.setAction(Intent.ACTION_VIEW);
//        intent.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
//        context.startActivity(intent);
//
//    }

    /**
     * android7.x
     * @param
     */
    public void installApk(Context context,int appId) {
        //参数1 上下文, 参数2 在AndroidManifest中的android:authorities值, 参数3  共享的文件
        File file = new File(mSavePath, "mobilelife.apk");
        String filePath=getPackageName(file.getPath(),context);
        SharedPreferences sharedPreferences = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
        String  packageNameList = sharedPreferences.getString("packageNameList", null);
        if (TextUtils.isEmpty(packageNameList)){
            JSONArray jsonArray=new JSONArray();
            JSONObject packageNameListJSONObject=new JSONObject();
            try {
                packageNameListJSONObject.put(appId+"",filePath);
                jsonArray.put(packageNameListJSONObject);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("packageNameList",jsonArray.toString());
                editor.commit();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }else {
            try {
                JSONArray jsonArray=new JSONArray(packageNameList);
                JSONObject packageNameListJSONObject=new JSONObject();
                packageNameListJSONObject.put(appId+"",filePath);
                jsonArray.put(packageNameListJSONObject);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("packageNameList",jsonArray.toString());
                editor.commit();
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if(Build.VERSION.SDK_INT>=24) { //Android 7.0及以上
            // 参数2 清单文件中provider节点里面的authorities ; 参数3  共享的文件,即apk包的file类
            Uri apkUri = FileProvider.getUriForFile(context, "com.launcher.wkang.provider", file);
            //对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        }else{
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);

    }






    /** 
      * 
      * 通过APK地址获取此APP的包名和版本等信息 
      * */
    private String getPackageName(String path, Context context) {
//        String FilePath="*.apk";//输入APK地址
        PackageManager pm = context.getPackageManager();
        PackageInfo info = pm.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES);
        if(info != null){
            ApplicationInfo appInfo = info.applicationInfo;
            String appName = pm.getApplicationLabel(appInfo).toString();
            String packageName = appInfo.packageName; //获取安装包名称 
            Log.i("Abel_Test", "包名是："+packageName);
            String version=info.versionName; //获取版本信息 
            Log.i("Abel_Tes", "版本信息："+version);
            return packageName;

        }
        return null;

    }








}
